<template>
  <el-row>
    <el-col :span="6" style="height: 100%; border-right: 1px solid #dfe6ec">
      <!-- <div class="app-container calendar-list-container">
        <div id="treeBox" class="filter-container"> -->
      <!-- <el-table :data="treeList" style="width: 100%;" row-key="id" border lazy :load="load" @row-click="getListByTreeId">
            <el-table-column prop="name" label="名称" sortable />
          </el-table> -->
      <div class="comp-tree">
        <!--            <el-button class="comp-tr-top" type="primary" size="small" @click="handleAddTop">添加顶级节点</el-button>-->
        <el-button class="comp-tr-top" type="primary" size="small" @click="handleAddTop" style="width: 100%">添加顶级节点</el-button>
        <!-- tree -->
        <el-input placeholder="输入关键字进行过滤~" v-model="filterText"> </el-input>
        <el-tree
          ref="SlotTree"
          :data="treeList"
          :props="defaultProps"
          :current-node-key="currentNodekey"
          :filter-node-method="filterNode"
          :expand-on-click-node="false"
          highlight-current
          :node-key="NODE_KEY"
          @node-click="handleNodeClick"
          style="margin-top: 1rem"
        >
          <div class="comp-tr-node" slot-scope="{ node, data }">
            <i v-if="data.parentId === '0'" class="el-icon-folder"></i>
            <i v-else class="el-icon-collection-tag"></i>
            <!-- 编辑状态 -->
            <template v-if="node.isEdit">
              <el-input v-model="data.name" autofocus size="mini" :ref="'slotTreeInput' + data[NODE_KEY]" @blur.stop="handleInput(node, data)" @keyup.enter.native="handleInput(node, data)"></el-input>
            </template>

            <!-- 非编辑状态 -->
            <template v-else>
              <!-- 名称： 新增节点增加class（is-new） -->
              <el-tooltip class="item" effect="dark" :content="node.label" placement="top-start">
                <span :class="[data[NODE_KEY] < NODE_ID_START ? 'is-new' : '', 'comp-tr-node--name']">
                  {{ node.label }}
                </span>
              </el-tooltip>

              <!-- 按钮 -->
              <el-dropdown placement="top" style="margin-left: 10%">
                <span class="el-dropdown-link">
                  <i class="el-icon-more el-icon--right"></i>
                </span>
                <el-dropdown-menu>
                  <!-- 新增 -->
                  <el-tooltip class="item" effect="dark" content="添加子节点" placement="top">
                    <el-button
                      icon="el-icon-plus"
                      size="large"
                      circle
                      title="添加子节点"
                      @click="handleAdd(node, data)"
                      style="border: none; background-color: transparent; transform: scale(1.1)"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="查看详情" placement="top">
                    <!-- 查看 -->
                    <el-button
                      icon="el-icon-document"
                      size="large"
                      circle
                      title="查看节点详情"
                      @click="handleLook(node, data)"
                      style="border: none; background-color: transparent; transform: scale(1.1)"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="编辑节点" placement="top">
                    <el-button
                      icon="el-icon-edit"
                      size="large"
                      circle
                      title="编辑节点"
                      @click="handleEdit(node, data)"
                      style="border: none; background-color: transparent; transform: scale(1.1)"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" content="删除节点" placement="top">
                    <el-button
                      icon="el-icon-delete"
                      size="large"
                      circle
                      title="删除节点"
                      @click="handleDeletetree(node, data)"
                      style="border: none; background-color: transparent; transform: scale(1.1)"
                    ></el-button>
                  </el-tooltip>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </div>
        </el-tree>
      </div>
      <!-- </div>
      </div> -->
    </el-col>
    <el-col :span="18">
      <div class="app-container">
        <div class="filter-container">
          <div class="filter-item">
            <span class="span">表名 </span>
            <el-input v-model="listQuery.tableName" placeholder="请输入表名" style="width: 200px" />
          </div>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            {{ $t('table.search') }}
          </el-button>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-plus" @click="handleBind">
            {{ $t('table.bind') }}
          </el-button>
        </div>

        <el-table
          ref="table"
          :key="tableKey"
          v-loading="listLoading"
          element-loading-text="正在加载，请稍后"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%"
          @selection-change="handleSelectionChange"
          max-height="400px"
        >
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column type="index" align="center" label="序号" width="50" />
          <el-table-column label="所属数据源" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.sourceName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="表名" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.tableName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="表注释" align="center" min-width="150px">
            <template slot-scope="{ row }">
              <span>{{ row.tableComment }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" min-width="230" class-name="small-padding fixed-width">
            <template slot-scope="{ row }">
              <el-button v-permission="['masterdata:MasterdataTable:update']" type="text" size="small" icon="el-icon-document" @click="handleDetail(row)">
                {{ $t('table.look') }}
              </el-button>
              <el-button v-permission="['masterdata:MasterdataTable:delete']" type="text" size="small" icon="el-icon-delete" class="delete-text-btn" @click="handleDelete(row)">
                {{ $t('table.relieve') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <import ref="import" template-url="/masterdata/MasterdataTable/template" import-url="/masterdata/MasterdataTable/import" @refreshList="getList" />
        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" :page-sizes="pageArray" @pagination="getList" />

        <masterdata-table-form ref="form" @refreshList="getList" />
        <treeData ref="treeForm" @getTreeList="getTreeList" />
        <bindData ref="listData" @getList="getList" />
        <checkDetail ref="checkDetail" />
      </div>
    </el-col>
  </el-row>
</template>

<script>
import { fetchMasterdataDirectoryList, createMasterdataDirectory, updateMasterdataDirectory, getMasterdataDirectory, deleteMasterdataDirectory } from '@/api/masterdata/masterdataDirectory'
import { deleteMasterdataTable, fetchMasterdataTableList, exportMasterdataTable, getMasterdataTable } from '@/api/masterdata/masterdataTable'
import { bindTable } from '@/api/masterdata/bindData'
import Import from '@/components/Import/import'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission/permission'
import masterdataTableForm from './masterdataTableForm'
import Pagination from '@/components/Pagination'
import treeData from './treeData.vue'
import bindData from './bindData.vue'
import checkDetail from './checkDetail.vue'

export default {
  name: 'MasterdataTableList',
  components: { masterdataTableForm, Pagination, Import, treeData, bindData, checkDetail },
  directives: { waves, permission },
  data() {
    return {
      filterText: '',
      tableKey: 0,
      treeList: [],
      list: null,
      total: 0,
      multipleSelection: [],
      downloadLoading: false,
      listLoading: true,
      pageArray: this.$store.getters.pageArray,
      listQuery: {
        tableName: undefined,
        page: 1,
        limit: this.$store.getters.defaultPageSize,
        ancestralId: '0',
      },
      isLoading: false, // 是否加载
      NODE_KEY: 'id', // id对应字段
      MAX_LEVEL: 5, // 设定最大层级

      NODE_ID_START: 0, // 新增节点id，逐次递减
      startId: null,
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      initParam: {
        // 新增参数
        name: '新增节点',
        parentId: 0,
        children: [],
      },
      directoryId: '', //选中目录ID
      currentNodekey: '',
    }
  },
  computed: {
    ids() {
      const ids = []
      this.multipleSelection.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids.join(',')
    },
  },
  created() {
    this.getTreeList()
    // this.getList()
  },
  watch: {
    filterText(val) {
      this.$refs.SlotTree.filter(val)
    },
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getTreeList() {
      this.listLoading = true
      fetchMasterdataDirectoryList(this.listQuery).then((response) => {
        if (response.data.code == 200) {
          this.treeList = response.data.data
          if (this.treeList.length > 0) {
            this.listQuery.directoryId = this.treeList[0].children[0].id
            this.currentNodekey = this.treeList[0].id
            this.getList()
            this.$nextTick(() => {
              this.$refs.SlotTree.setCurrentKey(this.currentNodekey) //一定要加这个选中了否则样式没有出来
            })
          }
          this.listLoading = false
          this.$refs.form.setList(this.treeList)
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    load(tree, treeNode, resolve) {
      resolve(tree.children)
    },
    getListByTreeId(data) {
      this.listQuery.directory_id = data.id
      this.getList()
    },
    getList() {
      this.listLoading = true

      fetchMasterdataTableList(this.listQuery).then((response) => {
        this.list = response.data.data.records
        this.total = response.data.data.total
        this.listLoading = false
      })
    },
    // getTableList(){
    //   getMasterdataTable({directoryId:this.directoryId}).then(res=>{
    //   console.log(res,'表数据')
    //   if(res.data.code==200){
    //     this.list = res.data.data?res.data.data.records:[]
    //   }else{
    //     this.$message.error(res.data.msg)
    //   }
    // })
    // },
    handleNodeClick(data) {
  
      this.listQuery.directoryId = data.id
      //  this.directoryId=data.id
      this.getList()
    },
    handleBind() {
      if (!this.listQuery.directoryId) {
        this.$message.warning('请选择目录')
        return
      }
      this.$refs.listData.handleCreate(this.listQuery.directoryId)
    },
    handleCreate() {
      this.$refs.form.setList(this.treeList)
      this.$refs.form.handleCreate()
    },
    handleUpdate(row) {
      this.$refs.form.setList(this.treeList)
      this.$refs.form.handleUpdate(row.id)
    },
    //查看详情
    handleDetail(row) {
      //  console.log(row)
      this.$refs.checkDetail.handleCreate(row.id)
    },
    handleDelete(row) {
      this.$confirm('确定删除该数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          bindTable({ tableId: row.id }).then((response) => {
            if (response.data.code === 0) {
              this.getList()
              this.$message.success(response.data.msg)
            } else {
              this.$message.error(response.data.msg)
            }
          })
        })
        .catch(() => {})
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleBathDelete() {
      if (this.ids === '') {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定删除所选数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteMasterdataTable(this.ids).then((response) => {
          if (response.data.code === 0) {
            this.getList()
            this.$message.success(response.data.msg)
          } else {
            this.$message.error(response.data.msg)
          }
        })
      })
    },
    handleImport() {
      this.$refs.import.show()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDeletetree(_node, _data) {
      // 删除节点

      console.log(_node, _data)
      // 判断是否存在子节点
      if (_data.children && _data.children.length !== 0) {
        this.$message.error('此节点有子级，不可删除！')
        return false
      } else {
        // 删除操作
        let DeletOprate = () => {
          this.$nextTick(() => {
            if (this.$refs.SlotTree) {
              deleteMasterdataDirectory(_data.id).then((res) => {
                 
                this.$message.success('删除成功！')
                this.$refs.SlotTree.remove(_data)
              })
            }
          })
        }

        // 二次确认
        let ConfirmFun = () => {
          this.$confirm('是否删除此节点？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              DeletOprate()
            })
            .catch(() => {})
        }

        // 判断是否新增： 新增节点直接删除，已存在的节点要二次确认
        _data[this.NODE_KEY] < this.NODE_ID_START ? DeletOprate() : ConfirmFun()
      }
    },
    handleInput(_node, _data) {
      // 修改节点
      console.log(_node, _data)

      // updateMasterdataDirectory(obj).then(res=>{
      //   if(res.data.code==0){
      //     this.$message.success(res.data.msg)
      //     this.getTreeList()
      //   }else{
      //     this.$message.error(res.data.msg)
      //   }
      // })
      // 退出编辑状态
      if (_node.isEdit) {
        this.$set(_node, 'isEdit', false)
      }
    },
    handleLook(_node, _data) {
      let obj = {
        id: _data.id,
        parentId: _data.parentId,
        name: _data.name,
        description: _data.description,
      }
      this.$refs.treeForm.handleLook(obj, 0)
    },
    handleEdit(_node, _data) {
      // 编辑节点
      console.log(_node, _data)
      let obj = {
        id: _data.id,
        parentId: _data.parentId,
        name: _data.name,
        description: _data.description,
      }
      this.$refs.treeForm.handleUpdate(obj, 0)
      // // 设置编辑状态
      // if(!_node.isEdit){
      // 	this.$set(_node, 'isEdit', true)
      // }

      // // 输入框聚焦
      // this.$nextTick(() => {
      // 	if(this.$refs['slotTreeInput'+_data[this.NODE_KEY]]){
      // 		this.$refs['slotTreeInput'+_data[this.NODE_KEY]].$refs.input.focus()
      // 	}
      // })
    },
    handleAdd(_node, _data) {
      // 新增节点
      console.log(_node, _data)
      // // 判断层级
      if (_node.level >= this.MAX_LEVEL) {
        this.$message.warning('当前已达到' + this.MAX_LEVEL + '级，无法新增！')
        return false
      }
      // 参数修改
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.parentId = _data.id // 父id
      obj.name = ''
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      this.$refs.treeForm.handleCreate(obj, 0)
      // 判断字段是否存在
      // if(!_data.children){
      // 	this.$set(_data, 'children', [])
      // }
      // 展开节点
      // if(!_node.expanded){
      // 	_node.expanded = true
      // }
    },
    handleAddTop() {
      // 添加顶部节点
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.parentId = 0
      obj.name = ''
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      // console.log(obj,'顶部参数')
      this.$refs.treeForm.handleCreate(obj, 0)
    },
  },
}
</script>
<style lang="scss" scoped>
::v-deep(::-webkit-scrollbar) {
  display: block !important;
}
#treeBox {
  overflow-x: auto;
  margin-top: 1px;

  .el-table thead {
    display: none;
  }
}

.el-tree {
  min-width: 250px;
}

.show-btns {
  opacity: 1;
}

/* common end */

.comp-tree {
  // min-width: 800px;
  height: 80vh;
  overflow: auto;
  box-sizing: border-box;
  // padding: 1.8em;

  // overflow-y: auto;
  // 顶部按钮
  .comp-tr-top {
    width: 100px;
    margin-bottom: 2em;
  }

  // 自定义节点
  .comp-tr-node {
    // label
    .comp-tr-node--name {
      // display: inline-block;
      // line-height: 40px;
      // min-height: 40px;

      // 新增
      &.is-new {
        // font-weight: bold;
      }
    }

    // button
    .comp-tr-node--btns {
      margin-left: 10px;
      opacity: 0;
      transition: opacity 0.1s;

      .el-button {
        transform: scale(0.8); // 缩小按钮

        & + .el-button {
          margin-left: -1px;
        }
      }
    }
  }

  // 高亮显示按钮
  .is-current {
    & > .el-tree-node__content {
      .comp-tr-node--btns {
        @extend .show-btns;
      }
    }
  }

  // 悬浮显示按钮
  .el-tree-node__content {
    &:hover {
      .comp-tr-node--btns {
        @extend .show-btns;
      }
    }
  }
}

.span {
  color: #606266;
  font-weight: 700;
  font-size: 14px;
}
</style>
